#!/bin/bash

#请根据自己情况修改下面的代码

magisk_path=/root/Magisk  #脚本创建的所有文件的保存目录

#获取最新stable magisk版本号
new_ver=$(
        wget -t2 -T3 -qO- "https://raw.githubusercontent.com/HuskyDG/magisk-files/main/stable.json" | grep -o '"version": ".*"' | cut -d'"' -f4
    )
#获取最新stable note版本号
note_ver=$(
        wget -t2 -T3 -qO- "https://raw.githubusercontent.com/HuskyDG/magisk-files/main/stable.json" | grep -o '"versionCode": ".*"' | head -n 1 | cut -d'"' -f4 
    )
#获取最新stable stub版本号
stub_ver=$(
        wget -t2 -T3 -qO- "https://raw.githubusercontent.com/HuskyDG/magisk-files/main/stable.json" | grep -o '"versionCode": ".*"' | cut -d'"' -f4 | sed '1d'
    )
#获取app下载链接
app_link=$(
        wget -t2 -T3 -qO- "https://raw.githubusercontent.com/HuskyDG/magisk-files/main/stable.json" | grep -o '"link": ".*"' | head -n 1 | cut -d'"' -f4 
    )
#获取stub下载链接
stub_link=$(
        wget -t2 -T3 -qO- "https://raw.githubusercontent.com/HuskyDG/magisk-files/main/stable.json" | grep -o '"link": ".*"' | cut -d'"' -f4 | sed '1d'
    )
#获取note下载链接
note_link=$(
        wget -t2 -T3 -qO- "https://raw.githubusercontent.com/HuskyDG/magisk-files/main/stable.json" | grep -o '"note": ".*"' | head -n 1 | cut -d'"' -f4 
    )
#本地下载目录
path=$magisk_path/delta/stable/$new_ver
#如果文件夹不存在，创建文件夹
if [ ! -d "$magisk_path" ]; then 
    mkdir -p $magisk_path
else
    cd ~
fi
if [ ! -d "$magisk_path/delta/stable" ]; then 
    mkdir -p $magisk_path/delta/stable
fi
#如果文件不存在，创建文件
if [ ! -f "$magisk_path/ver_delta_stable.txt" ]; then
    cd $magisk_path
    echo "v00.0" > ver_delta_stable.txt
else
    cd ~
fi
#获取已有版本号
ver=$(
    cat $magisk_path/ver_delta_stable.txt
    )
#获取更新
if [[ $new_ver = $ver ]]
then
    echo "目前不需要更新"
else
    rm -rf $magisk_path/ver_delta_stable.txt
    mkdir $path
    wget $app_link -O $path/app-release.apk
    wget $stub_link -O $path/stub-release.apk
    wget $note_link -O $path/notes.md
    cd $magisk_path
    rm -rf $magisk_path/delta.json
    echo "{
  "\"magisk"\": {
    "\"version"\": "\"$new_ver"\",
    "\"versionCode"\": "\"$note_ver"\",
    "\"link"\": "\"https://pan.lm379.cn/d/magisk/delta/stable/$new_ver/app-release.apk"\",
    "\"note"\": "\"https://pan.lm379.cn/d/magisk/delta/stable/$new_ver/notes.md"\"
  },
  "\"stub"\": {
    "\"versionCode"\": "\"$stub_ver"\",
    "\"link"\": "\"https://pan.lm379.cn/d/magisk/delta/stable/$new_ver/stub-release.apk"\"
  }
}" > delta.json
    rm -rf $magisk_path/ver_delta_stable.txt
    rm -rf $magisk_path/delta/stable/$ver
    cd  $magisk_path
    echo "$new_ver" > ver_delta_stable.txt  #写入版本信息
    rclone copy $path webdav:/magisk/delta/stable/$new_ver/ --transfers=1   #上传文件并设定最大并行任务数为1，如不使用rclone请将这三行代码注释
    rclone delete webdav:/magisk/delta.json
    rclone copy $magisk_path/delta.json webdav:/magisk
    echo "更新完成"
fi
